﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Linq
{
    /// <summary>
    /// 字典扩展
    /// </summary>
    public static class DictionaryExtension
    {
        /// <summary>
        /// 添加键值（如果键已存在则放弃覆盖值）
        /// </summary>
        /// <typeparam name="TKey">键</typeparam>
        /// <typeparam name="TValue">值</typeparam>
        /// <param name="obj"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void AddOrKeep<TKey, TValue>(this IDictionary<TKey, TValue> obj, TKey key, TValue value)
        {
            if (obj.ContainsKey(key)) return;

            obj.Add(key, value);
        }

        /// <summary>
        /// 添加键值（如果键已存在则覆盖值）
        /// </summary>
        /// <typeparam name="TKey">键</typeparam>
        /// <typeparam name="TValue">值</typeparam>
        /// <param name="obj"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void AddOrReplace<TKey, TValue>(this IDictionary<TKey, TValue> obj, TKey key, TValue value)
        {
            if (obj.ContainsKey(key))
            {
                obj[key] = value;
                return;
            }

            obj.Add(key, value);
        }

        /// <summary>
        /// 循环遍历字典
        /// </summary>
        /// <typeparam name="TKey">键类型</typeparam>
        /// <typeparam name="TValue">值类型</typeparam>
        /// <param name="obj"></param>
        /// <param name="func">循环遍历回调函数</param>
        public static void ForEach<TKey, TValue>(this IDictionary<TKey, TValue> obj, Action<TKey, TValue> func)
        {
            if (func.IsNull()) return;

            foreach (var item in obj)
            {
                func(item.Key, item.Value);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="JoinString">连接字符</param>
        /// <param name="IsAfter">value加后面, false:value加前面</param>
        public static void AddOrAppend(this IDictionary<string, object> obj, string key, string value, string JoinString = " ", bool IsAfter = true)
        {
            if (obj.IsNull()) obj = new Dictionary<string, object>();

            if (obj.ContainsKey(key))
            {
                if (IsAfter)
                    obj[key] = obj[key].ToStr() + JoinString + value;
                else
                    obj[key] = value + JoinString + obj[key].ToStr();
            }
            else
            {
                obj.Add(key, value);
            }
        }
    }
}
